/**
 * 盲盒购买接口调用示例（重构后）
 * 
 * 功能：buy 接口现在包含自动抽奖逻辑
 * 优势：一次请求完成购买+抽奖，无需分别调用 buy 和 draw
 */

// ===== 示例1：购买单个盲盒 =====
async function buySingleBlindBox(blindBoxId, addressInfo) {
  try {
    const response = await fetch('/api/blindbox.buy', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        blind_box_id: blindBoxId,
        quantity: 1, // 购买1个
        payment_method: 'wechat',
        shipping_method: 'package',
        address: JSON.stringify(addressInfo),
        message: '请尽快发货'
      })
    });

    const result = await response.json();

    if (result.status === 0) {
      console.log('✅ 购买成功！');
      console.log('订单号：', result.order_no);
      console.log('订单ID：', result.order_id);

      // 🎉 抽奖结果已包含在响应中！
      if (result.draw_result) {
        console.log('🎁 恭喜抽中：', result.draw_result.prize.prize_name);
        console.log('奖品等级：', result.draw_result.prize.prize_level);
        console.log('奖品价值：', result.draw_result.prize.prize_value);
        
        // 显示抽奖动画
        showPrizeAnimation(result.draw_result.prize);
      }
    } else {
      console.error('❌ 购买失败：', result.description);
    }

    return result;
  } catch (error) {
    console.error('❌ 请求失败：', error);
    throw error;
  }
}


// ===== 示例2：购买多个盲盒（批量抽奖）=====
async function buyMultipleBlindBoxes(blindBoxId, quantity, addressInfo) {
  try {
    const response = await fetch('/api/blindbox.buy', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        blind_box_id: blindBoxId,
        quantity: quantity, // 购买多个
        payment_method: 'wechat',
        shipping_method: 'package',
        address: JSON.stringify(addressInfo),
        message: '批量购买'
      })
    });

    const result = await response.json();

    if (result.status === 0) {
      console.log(`✅ 购买成功！共购买 ${quantity} 个盲盒`);
      console.log('订单号：', result.order_no);

      // 🎉 批量抽奖结果
      if (result.draw_results && result.draw_results.length > 0) {
        console.log(`🎁 共抽中 ${result.draw_results.length} 个奖品：`);
        
        result.draw_results.forEach((drawResult, index) => {
          console.log(`  ${index + 1}. ${drawResult.prize.prize_name} (${drawResult.prize.prize_level})`);
        });

        // 显示批量抽奖结果
        showBatchPrizeResults(result.draw_results);
      }

      // 检查是否有抽奖失败的情况
      if (result.draw_errors && result.draw_errors.length > 0) {
        console.warn('⚠️ 部分抽奖失败：', result.draw_errors);
      }
    } else {
      console.error('❌ 购买失败：', result.description);
    }

    return result;
  } catch (error) {
    console.error('❌ 请求失败：', error);
    throw error;
  }
}


// ===== 示例3：Vue3 组件中使用 =====
export default {
  name: 'BlindBoxPurchase',
  methods: {
    async handleBuy() {
      const blindBoxId = this.currentBlindBox.id;
      const quantity = this.purchaseQuantity;
      
      // 准备地址信息
      const addressInfo = {
        name: this.address.name,
        telephone: this.address.phone,
        province_name: this.address.province,
        city_name: this.address.city,
        area_name: this.address.area,
        detail_address: this.address.detail
      };

      // 显示加载动画
      this.loading = true;

      try {
        const result = await this.$http.post('/api/blindbox.buy', {
          blind_box_id: blindBoxId,
          quantity: quantity,
          payment_method: 'wechat',
          shipping_method: 'package',
          address: JSON.stringify(addressInfo)
        });

        if (result.status === 0) {
          // 购买成功
          this.$message.success('购买成功！');

          // 跳转到支付页面（如果需要支付）
          if (!result.paid) {
            this.$router.push({
              name: 'Payment',
              params: { orderId: result.order_id }
            });
          } else {
            // 已支付，显示抽奖结果
            if (quantity === 1 && result.draw_result) {
              // 单个抽奖
              this.showPrizeModal(result.draw_result.prize);
            } else if (result.draw_results) {
              // 批量抽奖
              this.showBatchPrizeModal(result.draw_results);
            }
          }
        } else {
          this.$message.error(result.description || '购买失败');
        }
      } catch (error) {
        console.error('购买失败：', error);
        this.$message.error('网络错误，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    // 显示单个奖品弹窗
    showPrizeModal(prize) {
      this.prizeModalVisible = true;
      this.currentPrize = prize;
      // 播放抽奖动画...
    },

    // 显示批量奖品弹窗
    showBatchPrizeModal(drawResults) {
      this.batchPrizeModalVisible = true;
      this.prizes = drawResults.map(r => r.prize);
      // 播放批量抽奖动画...
    }
  }
};


// ===== 示例4：自提方式 =====
async function buyWithPickup(blindBoxId, pickupInfo) {
  const response = await fetch('/api/blindbox.buy', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      blind_box_id: blindBoxId,
      quantity: 1,
      payment_method: 'wechat',
      shipping_method: 'pickup', // 自提
      pickup_person: pickupInfo.name,
      pickup_phone: pickupInfo.phone,
      pickup: JSON.stringify(pickupInfo.pickupPoint)
    })
  });

  const result = await response.json();

  if (result.status === 0 && result.draw_result) {
    console.log('🎁 抽中奖品：', result.draw_result.prize.prize_name);
  }

  return result;
}


// ===== 响应数据结构示例 =====

/**
 * 单个盲盒购买响应：
 * {
 *   "status": 0,
 *   "order_id": 12345,
 *   "order_no": "BB12345678901234567890",
 *   "description": "购买成功！恭喜您抽中：iPhone 15 Pro",
 *   "paid": true,
 *   "draw_result": {
 *     "record_id": 1001,
 *     "prize": {
 *       "id": 5,
 *       "prize_name": "iPhone 15 Pro",
 *       "prize_image": "https://...",
 *       "prize_level": "SSR",
 *       "prize_value": "7999.00",
 *       "prize_type": "goods"
 *     }
 *   },
 *   "prize": { ... }, // 向后兼容字段，与 draw_result.prize 相同
 *   "draw_results": [ ... ] // 包含单个结果的数组
 * }
 */

/**
 * 多个盲盒购买响应：
 * {
 *   "status": 0,
 *   "order_id": 12346,
 *   "order_no": "BB12345678901234567891",
 *   "description": "购买成功！共抽中 3 个奖品",
 *   "paid": true,
 *   "draw_results": [
 *     {
 *       "record_id": 1002,
 *       "prize": { "prize_name": "iPhone 15 Pro", ... }
 *     },
 *     {
 *       "record_id": 1003,
 *       "prize": { "prize_name": "AirPods Pro", ... }
 *     },
 *     {
 *       "record_id": 1004,
 *       "prize": { "prize_name": "谢谢参与", ... }
 *     }
 *   ]
 * }
 */

/**
 * 部分抽奖失败响应：
 * {
 *   "status": 0,
 *   "order_id": 12347,
 *   "order_no": "BB12345678901234567892",
 *   "description": "购买成功！共抽中 2 个奖品",
 *   "paid": true,
 *   "draw_results": [ ... ], // 2个成功的结果
 *   "draw_errors": [
 *     "第3次抽奖失败：暂无可用奖品"
 *   ]
 * }
 */

/**
 * 所有抽奖失败响应：
 * {
 *   "status": 1,
 *   "order_id": 12348,
 *   "order_no": "BB12345678901234567893",
 *   "description": "订单创建成功，但抽奖失败：第1次抽奖失败：暂无可用奖品",
 *   "draw_errors": [
 *     "第1次抽奖失败：暂无可用奖品"
 *   ]
 * }
 */


// ===== 废弃的 draw 接口调用（不推荐使用）=====
// ❌ 旧方式（已废弃）
async function oldWayDontUse() {
  // 1. 先购买
  const buyResult = await fetch('/api/blindbox.buy', { ... });
  
  // 2. 再抽奖（此接口已废弃！）
  const drawResult = await fetch('/api/blindbox.draw', {
    method: 'POST',
    body: JSON.stringify({
      blind_box_id: 1,
      order_id: buyResult.order_id
    })
  });
  // 响应：{"status": 1, "description": "此接口已废弃，请使用购买接口（buy）..."}
}

// ✅ 新方式（推荐）
async function newWayRecommended() {
  // 一次调用完成购买+抽奖
  const result = await fetch('/api/blindbox.buy', { ... });
  
  if (result.draw_result) {
    // 直接获取抽奖结果
    console.log('中奖了：', result.draw_result.prize.prize_name);
  }
}


// ===== 工具函数 =====

// 格式化地址信息
function formatAddress(address) {
  return {
    name: address.consignee,
    telephone: address.mobile,
    province_name: address.province,
    city_name: address.city,
    area_name: address.district,
    detail_address: address.address
  };
}

// 显示抽奖动画（示例）
function showPrizeAnimation(prize) {
  // 实现抽奖动画逻辑
  console.log('🎊 播放抽奖动画...');
  console.log('🎁 恭喜获得：', prize.prize_name);
}

// 显示批量抽奖结果（示例）
function showBatchPrizeResults(drawResults) {
  console.log('🎊 批量抽奖结果：');
  drawResults.forEach((result, index) => {
    console.log(`  ${index + 1}. ${result.prize.prize_name}`);
  });
}
